package com.yueke.gemini.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
import java.util.Map.Entry;

/**
 * java统计英语单词词频并按降序排列
 * Created by admin on 2017/10/21.
 */
public class Frequence {
    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new FileReader("F:/source.txt"));
        List<String> lists = new ArrayList<String>();  		//存储过滤后单词的列表
        String readLine = null;
        while((readLine = br.readLine()) != null){
            String[] wordsArr1 = readLine.split(" ");  //过滤出只含有字母的    [^a-zA-Z] 非单独字母
            for (String word : wordsArr1) {
                if(word.length() != 0){
                    lists.add(word);
                }
            }
        }

        br.close();

        Map<String, Integer> wordsCount = new TreeMap<String,Integer>();  //存储单词计数信息，key值为单词，value为单词数


        for (String li : lists) {
            if(wordsCount.get(li) != null){
                wordsCount.put(li,wordsCount.get(li) + 1);
            }else{
                wordsCount.put(li,1);
            }

        }

        SortMap(wordsCount);

    }

    //按value的大小进行排序
    public static void SortMap(Map<String,Integer> oldmap){

        ArrayList<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(oldmap.entrySet());

        Collections.sort(list,new Comparator<Entry<String,Integer>>(){
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());  						//降序
            }
        });


        for(int i = 0; i<list.size(); i++){
            System.out.println(list.get(i).getKey()+ ": " +list.get(i).getValue());
            if(i == 99){
                break;
            }
        }
    }
}
